<template>
  <div class="container">
    <div class="panel pad-10">
      <div class="mar-b-20 flex v-align-c">
        <div>请选择一张照片</div>
      </div>
      <div class="align-l">
        <upload-img @upLoadSuccess="upLoadSuccess" @upLoadFail="upLoadFail" @uploadDelete="uploadDelete" :showTip=false
                    :maxLength=1 :count=1></upload-img>
      </div>
    </div>
    <div class="mar-10">
      <button size="default" class="primary-button" @click="doSave">确定</button>
    </div>
  </div>
</template>

<script>
  import UploadImg from '@/components/UploadImg1'
  import { doChangeCardBackgroundPic } from '@/api/home'

  export default {
    components: { UploadImg },
    data() {
      return {
        bgPic: {
          memberId: '',
          cardBackgroundPic: ''
        },
        files: [],
        isUploadFinish: false
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
    },
    mounted() {
      this.bgPic.memberId = this.getCustomerId
    },
    // 监听上传是否完成
    watch: {
      isUploadFinish(val) {
        if (this.isUploadFinish) {
          this.doSave()
        }
      }
    },
    methods: {
      upLoadSuccess(res) {
        console.log(res)
        this.files = res.files
      },
      upLoadFail(res) {
        console.log(res)
      },
      upLoadComplete() {
        console.log('complete')
      },
      uploadDelete(res) {
        console.log(res)
      },
      doSave() {
        if (!this.isUploadFinish) {
          if (this.files.length === 0) return this.$utils.showToast({ title: '请选择要上传的照片' })
          this.$utils.showToast({
            title: '图片上传中',
            icon: 'loading',
            duration: 150000,
            mask: true
          })
          // 开始上传文件
          this.doUpload()
        } else {
          // 上传完成，清除数据
          this.files = []
          // 保存数据
          doChangeCardBackgroundPic(this.bgPic).then((response) => {
            if (response.isError) return
            this.$utils.showToast({ title: '保存成功' })
            setTimeout(() => {
              this.$pt.switchTab({ url: '/pages/home/main' })
            }, 500)
          }).catch(() => {
          })
        }
      },
      doUpload() {
        const that = this
        let finishCount = 0
        this.files.forEach(file => {
          // 使用微信上传（只能单张上传）
          const uploadTask = that.$pt.uploadFile({
            url: process.env.BASE_API + '/common/uploadFiles',
            filePath: file,
            name: 'files',
            success(res) {
              const result = JSON.parse(res.data)
              if (result.code === 101) {
                that.bgPic.cardBackgroundPic = result.data[0]
              } else {
                that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
                finishCount--
              }
            },
            complete() {
              finishCount++
              if (that.files.length === finishCount) {
                that.isUploadFinish = true
              }
            }
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
          })
        })
      }
    }
  }
</script>

<style scoped>

</style>
